package horncomb.bpm.process.instance;

import java.util.UUID;

import horncomb.bpm.process.core.Token;
import horncomb.bpm.process.core.entity.NestedTokenEntity;
import horncomb.bpm.process.core.entity.TokenEntity;
import horncomb.bpm.process.entity.DefaultNestedTokenEntity;
import horncomb.bpm.process.entity.DefaultTokenEntity;
import horncomb.bpm.process.support.BizEntityRefer;

/**
 * @author Daniel
 */
public class DefaultTokenCreator implements TokenCreator {

	/**
	 * {@inheritDoc}
	 */
	public Token create(String processInstanceId, Token parentToken,
			Object contextModel) {
		DefaultToken token = null;
		if (contextModel instanceof TokenEntity) {
			if (parentToken != null) {
				token = new DefaultNestedToken(
						(NestedTokenEntity) contextModel, parentToken.getId(),
						processInstanceId);
				token.setState(parentToken.getState());
				token.setEnteredDate(parentToken.getEnteredDate());
			} else {
				token = new DefaultToken((TokenEntity) contextModel,
						processInstanceId);
			}
		} else {
			if (parentToken != null) {
				DefaultNestedTokenEntity entity = new DefaultNestedTokenEntity();
				entity.setId(UUID.randomUUID().toString());
				token = new DefaultNestedToken(entity, parentToken.getId(),
						processInstanceId);
				token.setState(parentToken.getState());
				token.setEnteredDate(parentToken.getEnteredDate());
			} else {
				DefaultTokenEntity entity = new DefaultTokenEntity();
				entity.setId(UUID.randomUUID().toString());
				token = new DefaultToken(entity, processInstanceId);
			}
		}
		if (contextModel instanceof BizEntityRefer) {
			token.setBizDefinitionId(((BizEntityRefer) contextModel)
					.getBizDefinitionId());
			token.setBizEntityId(((BizEntityRefer) contextModel)
					.getBizEntityId());
		}
		// TODO throw Exception
		return token;
	}
}
